package gov.kqqzyyy.monkey.clinicscreen.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.clinicscreen.R;
import gov.kqqzyyy.monkey.clinicscreen.adapter.ClinicInfoAdapter;
import gov.kqqzyyy.monkey.clinicscreen.broadcast.DownLoadReceiver;
import gov.kqqzyyy.monkey.clinicscreen.broadcast.UpdateReceiver;
import gov.kqqzyyy.monkey.clinicscreen.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.clinicscreen.mytools.DateUtil;
import gov.kqqzyyy.monkey.clinicscreen.mytools.MarqueeTextView;
import gov.kqqzyyy.monkey.clinicscreen.mytools.MyStringUtil;
import gov.kqqzyyy.monkey.clinicscreen.mytools.ProgressDialogFragment;
import gov.kqqzyyy.monkey.clinicscreen.mytools.SpeakTool;
import gov.kqqzyyy.monkey.clinicscreen.network.RetrofitUtil;
import gov.kqqzyyy.monkey.clinicscreen.network.base.BaseObserver;
import gov.kqqzyyy.monkey.clinicscreen.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.clinicscreen.objects.CallPatient_New;
import gov.kqqzyyy.monkey.clinicscreen.objects.ClinicDoctor_New;
import gov.kqqzyyy.monkey.clinicscreen.objects.ClinicPatient;
import gov.kqqzyyy.monkey.clinicscreen.objects.DoctorGroup_New;
import gov.kqqzyyy.monkey.clinicscreen.objects.WarnInfo;
import gov.kqqzyyy.monkey.clinicscreen.service.UpdateService;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@SuppressLint("NonConstantResourceId")
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.logo_img)
    ImageView imageView;
    @BindView(R.id.clinic_area_text)
    TextView mClinicAreaText;
    @BindView(R.id.clinic_datetime_text)
    TextView mTimeText;
    @BindView(R.id.clinic_version_text)
    TextView mVersionText;
    @BindView(R.id.clinic_called_text_1)
    TextView callTextView1;
    @BindView(R.id.clinic_called_text_2)
    TextView callTextView2;
    @BindView(R.id.clinic_patient_lv)
    ListView clinicPatientsLV;
    @BindView(R.id.clinic_bottom_info)
    MarqueeTextView marqueeTextView;

    private List<ClinicDoctor_New> newDoctorList;

    private List<ClinicPatient> patientList;
    private String pre_json = "";

    private List<CallPatient_New> newCallList;

    private MyHandler handler;
    private long deteDelta = 0;
    private Date localDateTime;
    private Timer clockTimer;

    private ProgressDialogFragment progressDialogFragment;
    private SharedPreferences mSharedPreferences;
    private Intent serviceIntent;
    private boolean isStoped = false;
    private UpdateReceiver updateReceiver;
    private DownLoadReceiver downLoadReceiver;
    private ClinicInfoAdapter adapter;
    private String ctrllerID;
    private String clinicArea;

    private CallThread callThread;

    private boolean isCalling = false;
    private SpeakTool speakTool;

    private static final int REQUESTPERMISSION = 110;
    private boolean PTMZGH = false;//普通门诊

    private boolean allPatientsZero;

    private boolean callWithDocName;

    private BaseObserver<String> timeObserver;
    private BaseObserver<WarnInfo> warnInfoBaseObserver;
    private BaseObserver<List<ClinicDoctor_New>> doctorObserver;
    private BaseObserver<List<ClinicPatient>> patientsObserver;
    private BaseObserver<List<CallPatient_New>> callObserver;
    private BaseObserver<String> updateObserver;

    private CountDownTimer doctorCountDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_v2);
        ButterKnife.bind(this);
//        handler = new MyHandler(this);
        handler = new MyHandler(this.getMainLooper(), MainActivity.this);
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        adapter = new ClinicInfoAdapter(this);
        clinicPatientsLV.setAdapter(adapter);

        serviceIntent = new Intent(getApplicationContext(), UpdateService.class);

        downLoadReceiver = new DownLoadReceiver(this);
        IntentFilter downLoadFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downLoadReceiver, downLoadFilter);
        updateReceiver = new UpdateReceiver(this);
        IntentFilter updateFilter = new IntentFilter("updatebroadcast");
        registerReceiver(updateReceiver, updateFilter);
        IntentFilter restartFilter = new IntentFilter();
        restartFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(SystemTimeReceiver, restartFilter);

        doStartService();

        speakTool = new SpeakTool(this);

        imageView.setOnClickListener(view -> {
            Intent intent = new Intent(getApplicationContext(), FragmentPreferences.class);
            startActivity(intent);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isStoped = false;
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        PTMZGH = sharedPreferences.getBoolean("normal_clinic_open", false);
//        doGetServerTime();
        doGetServerTime_New();
        //右上角时钟
        clockTimer = new Timer();
        clockTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 0x11;
                handler.sendMessage(message);
            }
        }, 1, 1000);
//        warnTimer = new Timer();
//        warnTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                Message message = new Message();
//                message.what = 0x20;
//                handler.sendMessage(message);
//            }
//        }, 1, 5000);
        String clinicName = mSharedPreferences.getString("clinicarea_name", "");
        ctrllerID = mSharedPreferences.getString("clinic_preference", "");
        clinicArea = mSharedPreferences.getString("clinic_area_preference", "1");
//        KLog.d("APE", "clinicArea:" + clinicArea);

        callWithDocName = mSharedPreferences.getBoolean("adddocname_preference", false);
        if (Objects.equals(clinicName, "")) {
            Toast.makeText(getApplicationContext(), "请先设置诊区！", Toast.LENGTH_SHORT).show();
        } else {
            mClinicAreaText.setText(clinicName);

            boolean showWarnInfo = sharedPreferences.getBoolean("warninfo_preference", false);
            if (showWarnInfo) {
                marqueeTextView.setVisibility(View.VISIBLE);
                doGetClinicWarnText();
            } else {
                marqueeTextView.setVisibility(View.GONE);
            }

            int textSize = 60;
            if (Objects.requireNonNull(clinicName).length() >= 4) {
//            if (Objects.equals(clinicName, "眼耳鼻喉科") || Objects.equals(clinicName, "治未病中心")) {
                textSize = 46;
//            }
            }

            mClinicAreaText.setTextSize(textSize);
        }
    }

    public void setWarnList() {
    }

    private void setWarnText(String warnText) {
//        if (warnList == null || !(warnList.size() > 0)) {
//            warnList = Arrays.asList(getResources().getStringArray(R.array.bottom_info));
//        }
//        marqueeTextView.setText(warnList.get(warnIndex));
//        warnIndex++;
//        if (warnIndex == warnList.size()) {
//            warnIndex = 0;
//        }
        marqueeTextView.setText(warnText);
    }

    //获取诊区通知信息
    private void doGetClinicWarnText() {
        Observable<BaseResponse<WarnInfo>> observable = RetrofitUtil.getInstence().getClinicWarnInfo(ctrllerID);
        warnInfoBaseObserver = new BaseObserver<>() {
            @Override
            protected void onSuccees(BaseResponse<WarnInfo> result) {
//                KLog.d("APE", result.getData());
                setWarnText(result.getData().getBigScreenRemarks());
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                KLog.d("APE", e);
            }

            @Override
            protected void onCodeError(BaseResponse<WarnInfo> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(warnInfoBaseObserver);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStoped = true;
        if (clockTimer != null) {
            clockTimer.cancel();
            clockTimer = null;
        }
//        if (warnTimer != null) {
//            warnTimer.cancel();
//            warnTimer = null;
//        }

        if (speakTool != null) {
            speakTool.destory();
        }
        stopCallThread();
        stopGetDataCalls();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downLoadReceiver);
        unregisterReceiver(updateReceiver);
        unregisterReceiver(SystemTimeReceiver);
        System.gc();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                Intent intent = new Intent(getApplicationContext(), FragmentPreferences.class);
                startActivity(intent);
//                finish();
                return true;
            case KeyEvent.KEYCODE_BACK:
                Intent intent1 = new Intent(getApplicationContext(), SplashActivity.class);
                startActivity(intent1);
                finish();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void doStartService() {
        //检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTPERMISSION);
        } else {
            startService(serviceIntent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTPERMISSION) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (serviceIntent != null) {
                        startService(serviceIntent);
                    }
                } else {//提示没有权限，安装不了咯
                    Toast.makeText(this, "没有存储读写权限，无法进行更新！", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public void doSetVersion() {
        String text = "版本号：" + CurrentVersion.getVerName(this);
        mVersionText.setText(text);
    }

    private static class MyHandler extends Handler {
        WeakReference<MainActivity> mActivity;

        MyHandler(@Nullable Looper looper, MainActivity activity) {
            super(Objects.requireNonNull(looper));
            mActivity = new WeakReference<>(activity);
        }

//        MyHandler(MainActivity activity) {
//            mActivity = new WeakReference<>(activity);
//        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case 0x11:
                    activity.setClock();
                    break;
//                case 0x20:
//                    activity.setWarnText();
//                    break;
                case 0x29:
                    int colorBlack = ContextCompat.getColor(activity, R.color.colorBlack);
                    int colorOrange = ContextCompat.getColor(activity, R.color.colorOrange);
                    activity.callTextView1.setTextColor(colorBlack);
                    activity.callTextView2.setTextColor(colorBlack);
                    if (msg.arg1 == 1) {
                        activity.callTextView2.setTextColor(colorOrange);
                    } else if (msg.arg1 == 0) {
                        activity.callTextView1.setTextColor(colorOrange);
                    } else {
                        activity.stopCallThread();
                        activity.doFlushData(3);
                    }
                    break;
            }
        }
    }

//    public void doGetServerTime() {
//        systemTimeCall = MyServiceUtil.getSystemTimeCall();
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(@NonNull Call<String> call, Response<String> response) {
//                String result = response.body();
//                if (result != null) {
//                    result = result.replace("\"", "");
//                    result = result.replaceAll("T", " ");
//                    Date serverDate = DateUtil.getDTFormatDateTime(result);
//                    if (serverDate != null) {
//                        deteDelta = serverDate.getTime() - new Date(System.currentTimeMillis()).getTime();
////                        Toast.makeText(getApplicationContext(), "系统时间已同步！", Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(@NonNull Call<String> call, Throwable t) {
//                Toast.makeText(getApplicationContext(), "获取服务器时间出错：" + t.toString(), Toast.LENGTH_SHORT).show();
//            }
//        };
//        systemTimeCall.enqueue(callback);
//    }

    public void doGetServerTime_New() {
        Observable<BaseResponse<String>> observable = RetrofitUtil.getInstence().getServerTime();
        timeObserver = new BaseObserver<>() {
            @Override
            protected void onSuccees(BaseResponse<String> result) {
                String timeResult = result.getData().replaceAll("T", " ");
                Date serverDate = DateUtil.getDTFormatDateTime(timeResult);
                if (serverDate != null) {
                    deteDelta = serverDate.getTime() - new Date(System.currentTimeMillis()).getTime();
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                KLog.d("APE", e);
            }

            @Override
            protected void onCodeError(BaseResponse<String> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(timeObserver);
    }

    //显示时间
    private void setClock() {
        localDateTime = new Date(System.currentTimeMillis());
        localDateTime.setTime(localDateTime.getTime() + deteDelta);
        String showDate = DateUtil.getWeekFormatDate(localDateTime);
        String text = showDate.substring(0, 11) + "\n" + showDate.substring(11, 14) + " " + showDate.substring(14);
        mTimeText.setText(text);
    }

    // 更新提示对话框
    public void showUpdateDialog(int newVerCode, String newVerName, String updateInfo) {
        cancelProgressDialog();
        String message = "";
        final Intent intent = new Intent("toUpdateService");
//        message += "当前版本：" + CurrentVersion.getVerName(this) + "\n";
//        message += "版本号：" + CurrentVersion.getVerCode(this) + "\n";
        message += "发现新版本：" + newVerName + "\n";
        message += "版本号：" + newVerCode + "\n";
        message += "更新内容：" + updateInfo + "\n";
        message += "是否更新？";
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    intent.putExtra("toservice", 0x11);
                    sendBroadcast(intent);
                    dialogInterface.dismiss();
                    showProgressDialog();
                })
                .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                .create();
        dialog.show();
    }

    public void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    public void showProgressDialog() {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage("下载中");
        progressDialogFragment.show(getFragmentManager(), "downLoading");
    }

    private final BroadcastReceiver SystemTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), Intent.ACTION_TIME_TICK)) {
                if (isRestartTime()) { //次日、11点 重启
                    new CountDownTimer(5000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                        }

                        @Override
                        public void onFinish() {
                            Intent intent1 = new Intent(getApplicationContext(), SplashActivity.class);
                            startActivity(intent1);
                            finish();
                        }
                    }.start();
                }
            }
        }
    };

    private boolean isRestartTime() {
        String timeNow = DateUtil.getDFFormatString(localDateTime);
        return timeNow.compareTo("23:59:55") > 0 || timeNow.compareTo("00:00:05") < 0 || (timeNow.compareTo("11:59:55") > 0 && timeNow.compareTo("12:00:05") < 0);
    }

    //获取诊区医生信息
//    private void doGetClinicDoctors() {
//        clinicDoctorsCall = MyServiceUtil.getClinicDoctorsCall(ctrllerID);
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(@NonNull Call<String> call, Response<String> response) {
//                String result = response.body();
//                if (result != null && !result.equals(doctorResult)) {
//                    Gson gson = new Gson();
//                    doctorResult = result;
//                    doctorList = gson.fromJson(result, new TypeToken<List<ClinicDoctor>>() {
//                    }.getType());
//                    HashSet<ClinicDoctor> h = new HashSet<>(doctorList);
//                    doctorList.clear();
//                    doctorList.addAll(h);
//                }
//                if (doctorList != null) {
//                    doGetClinicPatients();
//                    doGetCallPatients();
//                }
//            }
//
//            @Override
//            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
//                Toast.makeText(getApplicationContext(), "获取医生信息失败", Toast.LENGTH_SHORT).show();
//            }
//        };
//        clinicDoctorsCall.enqueue(callback);
//    }

    //获取诊区医生（新）
    private void doGetClinicDoctors_New() {
        String param = ctrllerID + "," + clinicArea;
        Observable<BaseResponse<List<ClinicDoctor_New>>> observable = RetrofitUtil.getInstence().getClinicDoctors(param);
        doctorObserver = new BaseObserver<List<ClinicDoctor_New>>() {

            @Override
            protected void onSuccees(BaseResponse<List<ClinicDoctor_New>> result) {
//                KLog.d("APE",new Date());
                newDoctorList = result.getData();
                if (null != newDoctorList && newDoctorList.size() > 0) {
//                    patientList = new ArrayList<>();
//                    newCallList = new ArrayList<>();
                    doSetData();
//                    pre_json = "";
                    doGetClinicPatients_New();
                    doGetCallPatients_New();
                } else {
                    doFlushData(1);
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                KLog.d("APE", e);
            }

            @Override
            protected void onCodeError(BaseResponse<List<ClinicDoctor_New>> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(doctorObserver);
    }

    //获取诊区病人（新）
    private void doGetClinicPatients_New() {
//        KLog.d("APE", "get patients data @ " + new Date());
        Observable<BaseResponse<List<ClinicPatient>>> observable = RetrofitUtil.getInstence().getClinicPatients(ctrllerID);
        patientsObserver = new BaseObserver<>() {
            @Override
            protected void onSuccees(BaseResponse<List<ClinicPatient>> result) {
                patientList = result.getData();
                Gson gson = new Gson();
                if (null != patientList && patientList.size() > 0) {
                    String json_str = gson.toJson(patientList);
                    if (!json_str.equals(pre_json)) {
                        pre_json = json_str;
                        doSetData();
                    } else {
                        if (allPatientsZero) {
                            doSetData();
                        } else {
                            doFlushData(2);
                        }

                    }
                } else {
                    doFlushData(2);
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                KLog.d("APE", e);
                doFlushData(2);
            }

            @Override
            protected void onCodeError(BaseResponse<List<ClinicPatient>> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
                doFlushData(2);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(patientsObserver);
    }

    //获取呼叫病人
    private void doGetCallPatients_New() {
//        KLog.d("APE", new Date() + " get call patients");
        String param = ctrllerID + "," + clinicArea;
        Observable<BaseResponse<List<CallPatient_New>>> observable = RetrofitUtil.getInstence().getCallPatients(param);
        callObserver = new BaseObserver<>() {
            @Override
            protected void onSuccees(BaseResponse<List<CallPatient_New>> result) {
                newCallList = result.getData();
                if (null != newCallList && newCallList.size() > 0 && !isCalling) {
//                    if (callWithDocName) {
                    doFindDoctors();
//                    } else {
//                        doCallPatients();
//                    }
                } else {
                    doFlushData(3);
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
//                KLog.d("APE", e);
                doFlushData(3);
            }

            @Override
            protected void onCodeError(BaseResponse<List<CallPatient_New>> t) {
                super.onCodeError(t);
//                KLog.d("APE", t);
                doFlushData(3);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callObserver);
    }

    //更新呼叫病人（新）
    private void updateCallPatient_New(int patientID) {
        Observable<BaseResponse<String>> observable = RetrofitUtil.getInstence().updateCallPatient(patientID);
        updateObserver = new BaseObserver<>() {
            @Override
            protected void onSuccees(BaseResponse<String> result) {
                KLog.d("APE", result);
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                KLog.d("APE", e);

            }

            @Override
            protected void onCodeError(BaseResponse<String> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(updateObserver);
    }

    private void doFindDoctors() {
        ArrayMap<DoctorGroup_New, List<ClinicPatient>> dataMap = adapter.getDataMap();

        if (dataMap != null) {
            Set<DoctorGroup_New> docSet = dataMap.keySet();
            for (CallPatient_New callpatient : newCallList
            ) {
                boolean found = false;
                for (DoctorGroup_New doctor : docSet
                ) {
                    if (found) {
                        break;
                    }
                    List<ClinicDoctor_New> docList = doctor.getList();
                    for (ClinicDoctor_New doctor_new : docList
                    ) {
                        if (callpatient.getZSMC().equals(doctor_new.getCzzs())) {
                            found = true;
                            callpatient.setYSXM(doctor_new.getYgxm());
                            break;
                        }
                    }
                }
            }
        }

        KLog.d("APE", newCallList);
        doCallPatients();
    }


    private void doCallPatients() {
        boolean ishide = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("hidename_preference", true);
        String text1;
        if (ishide) {
            text1 = "请 " + newCallList.get(0).getBRBH() + " 号 " + MyStringUtil.doHideName(newCallList.get(0).getBRXM()) + (newCallList.get(0).getYXJ().equals("20") ? "(回诊)" : "") + " 到 " + newCallList.get(0).getZSMC();
            if (callWithDocName) {
                text1 = text1 + "(" + newCallList.get(0).getYSXM() + ")";
            }
            text1 += " 就诊";
        } else {
            text1 = "请 " + newCallList.get(0).getBRBH() + " 号 " + newCallList.get(0).getBRXM() + (newCallList.get(0).getYXJ().equals("20") ? "(回诊)" : "") + " 到 " + newCallList.get(0).getZSMC();
            if (callWithDocName) {
                text1 = text1 + "(" + newCallList.get(0).getYSXM() + ")";
            }
            text1 += " 就诊";
        }
        if (newCallList.size() == 2) {
            callTextView1.setText(text1);
            String text2;
            if (ishide) {
                text2 = "请 " + newCallList.get(1).getBRBH() + " 号 " + MyStringUtil.doHideName(newCallList.get(1).getBRXM()) + (newCallList.get(1).getYXJ().equals("20") ? "(回诊)" : "") + " 到 " + newCallList.get(1).getZSMC();
                if (callWithDocName) {
                    text2 = text2 + "(" + newCallList.get(1).getYSXM() + ")";
                }
                text2 += " 就诊";
            } else {
                text2 = "请 " + newCallList.get(1).getBRBH() + " 号 " + newCallList.get(1).getBRXM() + (newCallList.get(1).getYXJ().equals("20") ? "(回诊)" : "") + " 到 " + newCallList.get(1).getZSMC();
                if (callWithDocName) {
                    text2 = text2 + "(" + newCallList.get(1).getYSXM() + ")";
                }
                text2 += " 就诊";
            }
            callTextView2.setText(text2);
        } else {
            String text2 = "";
            if (callTextView1.getText() != null) {
                text2 = (String) callTextView1.getText();
            }
            callTextView2.setText(text2);
            callTextView1.setText(text1);
        }

        boolean isCaller = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("sound_preference", true);
        if (isCaller) {
            stopCallThread();
            callThread = new CallThread();
            callThread.start();
        } else {
            doFlushData(3);
        }
    }

    private void stopCallThread() {
        if (callThread != null) {
            callThread.interrupt();
            callThread = null;
        }
    }

    private void doSetData() {
//        KLog.d("APE", "set data @ " + new Date());
        ArrayMap<DoctorGroup_New, List<ClinicPatient>> dataSet = new ArrayMap<>();
        if (newDoctorList != null && patientList != null) {
            List<DoctorGroup_New> keyList = new ArrayList<>();
//            List<ClinicDoctor> tempDocList = new ArrayList<>(doctorList);
            List<ClinicDoctor_New> tempDocList = new ArrayList<>(newDoctorList);
            for (int i = tempDocList.size() - 1; i >= 0; i = tempDocList.size() - 1) {
                DoctorGroup_New doctorGroup = new DoctorGroup_New();
//                List<ClinicDoctor> list = new ArrayList<>();
                List<ClinicDoctor_New> list = new ArrayList<>();
//                ClinicDoctor doctor = tempDocList.get(i);
                ClinicDoctor_New doctor = tempDocList.get(i);
                list.add(doctor);
//                doctorGroup.setSH(doctor.getSH());
                doctorGroup.setSH(doctor.getSxh());
                doctorGroup.setList(list);
                tempDocList.remove(i);

                if (PTMZGH) {//开启普通门诊功能
//                    if (doctor.getSFZJ() == 2) {
                    if (doctor.getGhlb() == null || doctor.getGhlb().equals("0") || doctor.getGhlb().equals("普通门诊")) {
                        for (int j = tempDocList.size() - 1; j >= 0; j--) {
//                            if (doctor.getCZHM().equals(tempDocList.get(j).getCZHM())) {
                            if (doctor.getDlh().equals(tempDocList.get(j).getDlh())) {
                                list.add(tempDocList.get(j));
                                tempDocList.remove(j);
//                                if (doctor.getSH() < doctorGroup.getSH()) {
                                if (doctor.getSxh() < doctorGroup.getSH()) {
                                    doctorGroup.setSH(doctor.getSxh());
                                }
                            }
                        }
                    }
                }
                keyList.add(doctorGroup);
            }
//            for (DoctorGroup group : keyList
            allPatientsZero = true;
            for (DoctorGroup_New group : keyList
            ) {
                List<ClinicPatient> list = new ArrayList<>();
//                for (ClinicDoctor doctor : group.getList()
                for (ClinicDoctor_New doctor : group.getList()
                ) {
                    for (int i = patientList.size() - 1; i >= 0; i--) {
                        ClinicPatient patient = patientList.get(i);
                        if (patient.getCZHM().equals(doctor.getDlh())) {
                            list.add(patient);
                            patientList.remove(patient);
                        }
                    }
                }
                if (list.size() > 0) {
                    allPatientsZero = false;
                    Collections.sort(list, (t0, t1) -> t0.getSXH() - t1.getSXH());
                }
                dataSet.put(group, list);
            }
//            KLog.d("APE", dataSet.size());
            adapter.setDataMap(dataSet);
//            for (ClinicDoctor doctor : doctorList
//            ) {
//                List<ClinicPatient> list = new ArrayList<>();
//                for (int i = patientList.size() - 1; i >= 0; i--) {
//                    ClinicPatient patient = patientList.get(i);
//                    if (patient.getCZHM().equals(doctor.getCZHM())) {
//                        list.add(patient);
//                        patientList.remove(patient);
//                    }
//                }
//                dataSet.put(doctor, list);
//            }
//            adapter.setDataMap(dataSet);
            doFlushData(2);
        }
    }

    //呼叫病人线程
    private class CallThread extends Thread {

        private int index = 0;
        private boolean keepCall = true;
        private boolean callNext = true;

        @Override
        public void run() {
            super.run();
            isCalling = true;
            while (keepCall) {
                if (callNext) {
                    callNext = false;
                    CallPatient_New patient = newCallList.get(index);
                    Message message = new Message();
                    message.what = 0x29;
                    message.arg1 = index;
                    handler.sendMessage(message);

                    String speakMessage = "请 " + patient.getBRBH() + " 号 " + patient.getBRXM() + " 到 " + patient.getZSMC();
                    if (callWithDocName) {
                        speakMessage = speakMessage + " " + patient.getYSXM();
                    }
                    speakMessage += " 就诊";
                    speakMessage += " " + speakMessage;
                    speakTool.speak(speakMessage, listener);
//                    updateCallPatient_New(patient.getID());
                }
                try {
                    SystemClock.sleep(1000);
//                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private final SynthesizerListener listener = new SynthesizerListener() {
            @Override
            public void onSpeakBegin() {
            }

            @Override
            public void onBufferProgress(int percent, int beginPos, int endPos, String info) {

            }

            @Override
            public void onSpeakPaused() {

            }

            @Override
            public void onSpeakResumed() {

            }

            @Override
            public void onSpeakProgress(int percent, int beginPos, int endPos) {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                if (index == newCallList.size() - 1) {
                    isCalling = false;
                    keepCall = false;
                    callNext = false;
                    Message message1 = new Message();
                    message1.what = 0x29;
                    message1.arg1 = -1;
                    handler.sendMessage(message1);
                } else {
                    index++;
                    callNext = true;
                }
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
            }
        };

    }

    public void doFlushData(int which) {
        if (!isStoped) {
            switch (which) {
                case 1:
                    if (!ctrllerID.equals("")) {
                        long timeMillis;
                        if (!isCalling) {
                            stopGetDataCalls();
//                            doGetClinicDoctors();
//                            KLog.d("APE",new Date());
                            doGetClinicDoctors_New();
                            timeMillis = 300000;
                        } else {
                            timeMillis = 20000;
                        }
                        if (doctorCountDownTimer != null) {
                            doctorCountDownTimer.cancel();
                        }
                        doctorCountDownTimer = new CountDownTimer(timeMillis, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {

                            }

                            @Override
                            public void onFinish() {
                                doFlushData(1);
                            }
                        };
                        doctorCountDownTimer.start();
                    }
                    break;
                case 2:
                    new CountDownTimer(4000, 2000) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
//                            doGetClinicPatients();
                            doGetClinicPatients_New();
                        }
                    }.start();
                    break;
                case 3:
                    if (!isCalling) {
                        new CountDownTimer(4000, 2000) {
                            @Override
                            public void onTick(long millisUntilFinished) {

                            }

                            @Override
                            public void onFinish() {
//                                doGetCallPatients();
                                doGetCallPatients_New();
                            }
                        }.start();
                    }
                    break;
            }
        }

    }

    private void stopGetDataCalls() {
        //        if (systemTimeCall != null && systemTimeCall.isExecuted()) {
//            systemTimeCall.cancel();
//        }
//        if (clinicDoctorsCall != null && clinicDoctorsCall.isExecuted()) {
//            clinicDoctorsCall.cancel();
//        }
//        if (clinicPatientsCall != null && clinicPatientsCall.isExecuted()) {
//            clinicPatientsCall.cancel();
//        }
//        if (callPatientCall != null && callPatientCall.isExecuted()) {
//            callPatientCall.cancel();
//        }
        if (warnInfoBaseObserver != null) {
            warnInfoBaseObserver.doCancelRequest();
        }
        if (doctorObserver != null) {
            doctorObserver.doCancelRequest();
        }
        if (patientsObserver != null) {
            patientsObserver.doCancelRequest();
        }
        if (callObserver != null) {
            callObserver.doCancelRequest();
        }
        if (updateObserver != null) {
            updateObserver.doCancelRequest();
        }
        if (timeObserver != null) {
            timeObserver.doCancelRequest();
        }
    }

//    /**
//     * 早上时间 7点45-8点半 ，医生信息刷新周期20s
//     */
//    private boolean isMorningTime() {
//        Date localDateTime = new Date(System.currentTimeMillis());
//        localDateTime.setTime(localDateTime.getTime() + deteDelta);
//        String timeNow = DateUtil.getDFFormatString(localDateTime);
//        return timeNow.compareTo("07:45:00") > 0 && timeNow.compareTo("08:30:00") < 0;
//    }

}
